<?php


class SiteFactory {
	
	private $pageRequest;
	/**
	 * @var Page
	 */
	private $page;
	
	
	
	private $smarty;
	private $pageHTML;
	private $siteHTML;
	
	private $designName;
	
	public function  __construct() {
		
		$cfg = Runtime::getConfiguration();
		
		
		$this->smarty = new Smarty();
		$this->smarty->compile_dir = $cfg["paths"]["tmp"] . "/cache/smarty";
		$this->smarty->plugins_dir = eCMS_DIR . "/app/lib/smarty/plugins";
		/*
		SmartyPaginate::connect();
		SmartyPaginate::assign($this->smarty);		
		*/
		
		//Because of Javascript
		/*
		$this->smarty->left_delimiter = "{*";
		$this->smarty->right_delemiter = "*}";
		*/
	}
	
	
	public function addPageRequest($req) {

		$this->pageRequest = $req; 
	}
	

	/**
	 * Loads the Page given by the prevois PageRequest and replaces the method-
	 * name and params with the one stored in the PageTable if they are set
	 *
	 */
	
	public function loadPage() {
		
		$pkPage = $this->pageRequest->getPkPage();
		try {
		$this->page = PageFactory::CreatePage($pkPage);
		}
		catch(Exception $e) {

			header("Status: 404", true, 404);
			Utils::jsRedirect("?");
			
		}
	
		//Modify the Page-Request by the Page Own Settings (loaded from tblPage)
		
		$item = new PageItem($this->page->getPkPage());
		
		$params = $item->params;
		$parsedParams = null;
		parse_str($params, $parsedParams);
		
		while((list($name, $value) = each($parsedParams))==true) {
			if($this->pageRequest->getGetVar($name)=="") {
				$this->pageRequest->setGetVar($name, $value);
				$_GET[$name] = $value;
			}
		}			
		
		//Replace the method if one is specified
		$method = $item->fkMethod;
		if($method && $this->pageRequest->getGetVar("method")=="") {
			$this->pageRequest->setMethod($method);
		}
		
		$this->page->setPageRequest($this->pageRequest);
		
	}
	
	public function invokeMethod() {
		
		Runtime::setCurrentMainPage($this->page);
		
		$this->page = PageFactory::invokeMethod($this->page, $this->pageRequest);
	}

	public function renderPage() {
		
		if(!$this->page->getIsPlainText()) {
			$this->pageHTML = PageFactory::renderPage($this->page);
		}
		else {
			$this->pageHTML = $this->page->getText();		
		}
		
	}

	public function renderSite() {
		
		//Let assigns in...
		//$this->smarty->clear_assigns();

		if(!isset($this->pageHTML)) {
			// Render first
			$this->renderPage();
		}
		
		if(!$this->page->getIsPlainText()) {
			
			$cfg = Runtime::getConfiguration();
			
			$designName = $this->page->getDesignName();	
			$designMode = $this->page->getDesignMode();
			
			/*
			 * Search the Design-Template for Page
			 * ===================================
			 * 
			 * 1. Try to search the Design in the Folger \content\design\{designname}
			 *    - Use the file "webpage-{desigmode}.tpl.php if designmode is set, otherwise:
			 *    - Use the file "webpage.tpl.php" if exists, otherwise:
			 * 2. Try to load the Design from the Shared template directory in the same manner as above
			 * 
			 */
			
			
			$tpl_basepaths[0] = array('path'=>$cfg["paths"]["page"]. "/content/design", 'url'=> 'content/design');
			$tpl_basepaths[1] = array('path'=>$cfg['sharedDesignPath'], 'url'=> $cfg['sharedDesignURL']);
			
			$fileWithMode = $designName . "/" . "webpage-" . $designMode . ".tpl.php";
			$fileWithoutMode = $designName . "/" . "webpage" . ".tpl.php";
			
			foreach ($tpl_basepaths as $tpl_basepath) {
				
				if(file_exists($tpl_basepath['path'])) {
					
					//Search the file here
					if(file_exists($tpl_basepath['path'] . "/" . $fileWithMode)) {
						$tpl_basepath["file"] = "webpage-$designMode.tpl.php";
						break;
					}
					
					if(file_exists($tpl_basepath['path'] . "/" . $fileWithoutMode)) {
						$tpl_basepath["file"] = "webpage.tpl.php";
						break;
					}
				}
			}

			if(!isset($tpl_basepath["file"])) {
				 
				Runtime::logEvent("TplForDesignNotFound", __FILE__, __CLASS__, __FUNCTION__, __LINE__, 
					array("tpl_path" => $tpl_basepaths,
						  "fileWithModeName"=>$fileWithMode,
					      "fileWithoutModeName"=>$fileWithoutMode));
					
				user_error("Template for Design not found! Sorry, can't display any content!");
				/* $tpl_path = $tpl_basepath . "/" . "standard" . "/" . "webpage" . ".tpl.php";
				$designname = "standard"; */
			}
			
			
			else {
			
				//Create Smarty ObjectArray Wrapper Class
		
				$w = new SmartyObjectArrayWrapper();
				$w->addObjectArray($this->getPrimaryNavigation(), "getPrimaryNavigation");
				
				$w->addObjectArray($this->page->getItemToolbox()->getItems(),     "getItemToolbox");
				$w->addObjectArray($this->page->getInstanceToolbox()->getItems(), "getInstanceToolbox");
				$w->addObjectArray($this->page->getModuleToolbox()->getItems(),   "getModuleToolbox");
				$w->addObjectArray($this->page->getPageToolbox()->getItems(),     "getPageToolbox");
				$w->addObjectArray($this->page->getSiteToolbox()->getItems(),     "getSiteToolbox");
				
				
				//Assign whole Page to Smarty
				$this->smarty->assign("page", $this->page);
				
				//Assign Current user to Smarty
				$this->smarty->assign("Sys_CurrentUser", SecurityUser::getUser());
				
				//Add other importand things
				
				$this->smarty->assign("Sys_CurrentGetQuery", $_SERVER['QUERY_STRING']);
				
				$this->smarty->assign("Sys_CurrentPageURL", "?page=".$this->page->getPkPage());
				$this->smarty->assign("Sys_DesignBasePath", $tpl_basepath['url'] . "/" . $designName);
				
				//JS Libs-Path
				$this->smarty->assign("Sys_JsLibsURL", $cfg['JsLibsURL']);
				
				$this->smarty->assign("Sys_SystemMessages", SecurityUser::getUser()->getSystemMessages());
					
				$this->smarty->assign("Sys_SiteFactory", $this);
				
				$this->smarty->assign("Sys_Wrapper", $w);
				$this->smarty->assign("Sys_PageContent", $this->pageHTML);
				$this->smarty->assign("Sys_Runtime", Runtime::getInstance());
	
				$this->siteHTML = $this->smarty->fetch($tpl_basepath['path'] . "/" . $designName . "/" . $tpl_basepath['file']);
			}
			
		}
		else {
			//The Page is plain-text
			$this->siteHTML = $this->pageHTML;
		}
	}
		
	public function echoSite() {
		echo $this->siteHTML;
	}
	
	public function getPageHTML() {
		return $this->pageHTML;
	}
	
	public function getSiteHTML() {
		return $this->siteHTML;
	}
	
	public function getPrimaryNavigation() {
		
		$cfg = Runtime::getConfiguration();
		$conn = MySQLConnection::getInstance();

		$nav = array();
		
		//$top = $this->page->getTopParent();
		
		//Load all TopPages from this Region
			$sql = "SELECT p.pkPage, p.fkArea, p.fkParentPage, p.fkModuleInstance, p.fkMethod, p.params, p.fkSecurityObject, mi.fkSecurityObject, p.fkCreateUser, p.createDate, 
						p.fkNestedPageSet, p.nestedPageMode, p.navTitle, p.sortId, p.navImage, p.pageTitle, p.isNavVisible, tablePostfix, m.pkModule, m.name, d.sysname, 
						p.fkPageLayout, pl.sysname AS  fkPageLayoutName
					FROM " . $cfg['table_prefix'] . "Page as p
					LEFT JOIN " . $cfg['table_prefix'] . "ModuleInstance as mi ON mi.pkModuleInstance = p.fkModuleInstance
					LEFT JOIN " . $cfg['table_prefix'] . "Module as m ON m.pkModule = mi.fkModule
					LEFT JOIN " . $cfg['table_prefix'] . "Area as a ON a.pkArea = p.fkArea
					LEFT JOIN " . $cfg['table_prefix'] . "Design as d ON d.pkDesign = a.fkDesign
					LEFT JOIN " . $cfg['table_prefix'] . "PageLayout as pl ON pl.pkPageLayout = p.fkPageLayout
		
					WHERE d.sysname='" . $this->page->getDesignName(). "' 
					ORDER BY p.sortId ASC 
				";
		
		$res = $conn->query($sql);

		while(($data = mysql_fetch_array($res))) {
			$p = new Page($data['pkPage'], null, $data);
			$p->getSubPages($this->page->getPkPage());
			array_push($nav, $p);
		}
			
		return $nav;
		
	}
	
	/**
	 * Returns the Page-Object of the current Request
	 *
	 * @return Page
	 */
	public function getPage() {
		return $this->page;
	}

}

?>